import webapp2
import models
import logging
import time
from google.appengine.api import users
from google.appengine.ext import db
from webapp2_extras import json
from google.appengine.api import oauth

class API(object):
    def ping(self,args=None):
        logging.info("Ping received")
        return {"result":"ok"}
    
    def syslog(self, args):
        logging.info(args)
        for content in args:
            syslog_entry = models.SyslogEntry()
            syslog_entry.content = json.encode(content)
            syslog_entry.put()
        return {"result":"ok"}
    
    def ls(self,args):
        logging.info(args)
        query = models.LogEntry.all()
        query.filter("user =",oauth.get_current_user())
        query.order("-date")
        if args["hostname"] != "all":
            query.filter("show_hostname =",args["hostname"])
        if args["username"] != "all":
            query.filter("show_username =",args["username"])
        entries = []
        for result in query.fetch(limit=10):
            entries.insert(0,{
                "content":result.content,
                "username":result.username,
                "show_username":result.show_username,
                "hostname":result.hostname,
                "show_hostname":result.show_hostname,
                "date":time.mktime(result.date.timetuple()),
                }
            )
        return {"result":"ok","entries":entries}

    def log(self, args):
        logging.info(args)
        log_entry = models.LogEntry()
        log_entry.content = args["content"]
        log_entry.hostname = args["hostname"]
        log_entry.username = args["username"]
        log_entry.user = oauth.get_current_user()
        log_entry.show_username = args["username"]
        if args.has_key("show_username"):
            log_entry.show_username = args["show_username"]
        log_entry.show_hostname = args["hostname"]
        if args.has_key("show_hostname"):
            log_entry.show_hostname = args["show_hostname"]
        log_entry.put()
        return {"result":"ok"}

    def user(self,args=None):
        logging.debug("sending user info")
        user = oauth.get_current_user()
        result = {"result":"ok","info":{"email":"None"} }
        if user:
            result = {"result":"ok","info":{"email":user.email()}}
        return result

class APIHandler(webapp2.RequestHandler):
    def handle_api(self):
        logging.info(self.request.body)
        args = []
        if self.request.body:
            args = json.decode(self.request.body)
        method_name = self.request.path.replace("/api", "").replace("/", "").strip()
        logging.info("POST request to method: %s" % method_name)
        self.response.headers["Content-Type"] = "application/json"
        api = API()
        response = {}
        user = None
        try:
            user = oauth.get_current_user()
            logging.debug("User authenticated: %s" % user.email())
        except oauth.OAuthRequestError, e:
            pass

        if not user:
            response["result"] = "error"
            response["error"] = "invalid_credentials"
            response["description"] = "Invalid authentication credentials"
        else:
            if hasattr(api, method_name):
                method = getattr(api, method_name)
                response = method(*args)
            else:
                response["result"] = "error"
                response["error"] = "invalid_method"
                response["description"] = "Invalid api call"
        self.response.out.write(json.encode(response))

    def get(self):
        self.handle_api()

    def post(self):
        self.handle_api()
